/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.activity;

import java.util.Random;

import org.sabayframework.activity.impl.State;
import org.sabayframework.activity.impl.StatefulActivity;
import org.sabayframework.channel.Lock;

/**
 * Activity takes as an input a long number and generates that many random numbers 
 * divided in arrays of a specified size. The array size is provided in the constructor. 
 * @author Alex Antonau
 * */
public class BatchRandom extends StatefulActivity<Long, double[]> {

	private long count=-1;
	private final int batchSize;
	private final Random random;
	private double[] batch;
	
	public BatchRandom(int batchSize) {
		this(batchSize, System.currentTimeMillis());
	}
	public BatchRandom(int batchSize, long randomSeed) {
		super();
		if(batchSize<=0)throw new IllegalArgumentException(String.valueOf(batchSize));
		this.batchSize = batchSize;
		this.random = new Random(randomSeed);
	}

	@Override
	public int getOutputSize(ActivityContext<Long, double[]> ctx) {
		return 1;
	}

	@Override
	public void input(ActivityContext<Long, double[]> ctx, Lock<Long> inputLock){
		count = inputLock.get(0).longValue();
	}

	@Override
	public State getState(ActivityContext<Long, double[]> ctx) {
		return count > 0 ? (batch == null? State.PROCESS : State.OUTPUT) : State.READY;
	}

	@Override
	public void process(ActivityContext<Long, double[]> ctx) throws Exception {
		int size = batchSize;
		if(count < batchSize) size= (int)count;
		batch = new double[size];
		for(int i=0;i<batch.length;++i) batch[i] = random.nextDouble();
	}
	@Override
	public void output(ActivityContext<Long, double[]> ctx, Lock<double[]> outputLock) throws Exception {
		outputLock.set(0, batch);
		count-=batch.length;
		batch = null;
	}
	

}
